package com.kiss.fw.utils.daemon;

import com.kiss.fw.dto.AbstractDTO;

public abstract class AbstractDaemon extends Thread {
	public static final short STATUS_RUNNING = 0;
	public static final short STATUS_COMPLETED = 1;
	public static final short STATUS_TERMINATED = 2;
	
	private short status = -1;
	private AbstractDTO dto;
	private Throwable error;
	
	protected AbstractDaemon() {
	}
	
	protected AbstractDaemon(final String _name) {
		this(null, _name);
	}
	
	protected AbstractDaemon(final AbstractDTO _dto, final String _name) {
		super(_name);
		dto = _dto;
	}
	
	protected AbstractDTO getDto() {
		return dto;
	}
	
	protected void setDto(final AbstractDTO _dto) {
		dto = _dto;
	}
	
	public boolean isRunning() {
		return STATUS_RUNNING == status;
	}
	
	public boolean isCompleted() {
		return STATUS_COMPLETED == status;
	}
	
	public boolean isTerminated() {
		return STATUS_TERMINATED == status;
	}
	
	public Throwable getError () {
		return error;
	}
	
	public void run() {
		try {
			status = STATUS_RUNNING;
			execute();
		}
		catch(Throwable _throwable) {
			error = _throwable;
		}
		finally {
			status = (error == null ? STATUS_COMPLETED : STATUS_TERMINATED);
		}
	}
	
	public abstract void execute();
}